package com.yudean.esb.util;

import com.yudean.esb.mapper.erp.ComplexQueryMapper;
import com.yudean.esb.plugins.component.SQLAdapter;
import com.yudean.esb.plugins.component.SelfMappers;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SqlMapBuilder {
    public static String build(SelfMappers mappers, int pageNo, int pageSize){
        String originalSql =  buildOriginalSQL(mappers);
        int offset = (pageNo - 1) * pageSize;
        String finalSql = new StringBuffer(
                "SELECT RS_.* FROM (SELECT ROW_.*, ROWNUM ROWNUM_ FROM (")
                .append(originalSql).append(") ROW_ ) RS_ WHERE ROWNUM_ > ")
                .append(offset).append(" AND ROWNUM_ <= ")
                .append(offset + pageSize).toString();
        return finalSql;
    }

    private static String buildOriginalSQL(SelfMappers mappers){
        String originalSql =  new SQL() {{
            //构造SELECT的选择列
            Map<String, String> primary = mappers.getPrimaryMap();
            //假设是将所有的列全部选择出来
            String from = " * ";
            //查看Map中是否已经存在了。
            if (primary != null) {
                Set<String> keySet = primary.keySet();
                Iterator<String> keys = keySet.iterator();
                StringBuffer sb = new StringBuffer();
                sb.append("  ");
                while (keys.hasNext()) {
                    sb.append(keys.next()).append(",");
                }
                sb.deleteCharAt(sb.length() - 1);
                sb.append(" ");
                from = sb.toString();
            }
            //SELECT
            SELECT(from);

            //查询的表名
            String tbName = mappers.getTbName();
            //TABLE
            FROM(tbName);

            //WHERE
            String where = mappers.getWhere();
            if (where != null)
                WHERE(where);
        }}.toString();
        return originalSql;
    }
    public static int getTotalRecord(SelfMappers mappers,DataSource dataSource){
        String sql = "SELECT COUNT(1) FROM (" + buildOriginalSQL(mappers) + ") RS_";
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("prod", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(ComplexQueryMapper.class);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<Object> list = sqlSession.selectList("com.yudean.esb.mapper.erp.ComplexQueryMapper.querySql", new SQLAdapter(sql));
        if(list!=null){
            return list.size();
        }
        return 0;
    }

}
